package com.itheima.rabbitmq.producer.config;

import com.itheima.rabbitmq.producer.service.MQTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * GY
 */
public class MessageDBTask implements Runnable {
    private MessageSender.MQMessage mqMessage;
    private Semaphore semaphore;
    private ApplicationContext context;
    private Logger logger = LoggerFactory.getLogger(MessageDBTask.class);

    public MessageDBTask(MessageSender.MQMessage mqMessage, Semaphore semaphore,
                         ApplicationContext context) {
        this.mqMessage = mqMessage;
        this.semaphore = semaphore;
        this.context = context;
    }

    private static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(3, 6, 3, TimeUnit.SECONDS,
                    new LinkedBlockingDeque<>(100)/*使用自定义拒绝策略，ERROR打印消息！略*/);

    @Override
    public void run() {
        // 任务落库
        MQTaskService mqTaskService = (MQTaskService) context.getBean("mQTaskService");
        mqTaskService.addTaskToDB(mqMessage);
        // 落库成功，释放信号量
        this.semaphore.release(); // 点亮信号灯
        logger.info("TASK ADD TO DB SUCCESS MESSAGE = {}",mqMessage);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("MessageDBTask{");
        sb.append("mqMessage=").append(mqMessage);
        sb.append(", semaphore=").append(semaphore);
        sb.append(", context=").append(context);
        sb.append('}');
        return sb.toString();
    }

    public void executor() {
        threadPoolExecutor.execute(this);
    }

}

